namespace Utils {

    import Dictionary = Laya.Dictionary;
    import Tween = Laya.Tween;
    export var RADIAN: number = 180 / Math.PI;

    /**
     * 地址转换简短
     */
    export function getShortAddress(address:string):string{
        return address.substring(0,5) + "..." + address.substring(address.length-5,address.length);
    }


    /**
     * 计算 距离
     * @param x1
     * @param y1
     * @param x2
     * @param y2
     * @return
     */
    export function dist(x1: number, y1: number, x2: number, y2: number): number {
        return (y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1);
    }

    export function getWay(x0: number, y0: number, x: number, y: number): number {
        return Number((Math.atan2(y - y0, x - x0) + 11.388) / 0.7854) % 8;
    }

    export function random(value1: number, value2: number): number {
        let value: number = Math.abs(value2 - value1);
        return Math.random() * value + value1;
    }

    var h: number = 60 * 60;
    var d: number = 60 * 60 * 24;
    export function toChineseTime(v: number): string {
        var year: number = parseInt(v / (d * 30 * 12) + "");
        if (year) v = parseInt(v % (d * 30 * 12) + "");
        var months: number = parseInt(v / (d * 30) + "");
        if (months) v = parseInt(v % (d * 30) + "");
        var day: number = parseInt(v / d + "");
        if (day) v = parseInt(v % d + "");
        var hour: number = parseInt(v / h + "");
        if (hour) v = parseInt(v % h + "");
        var minute: number = parseInt(v / 60 + "");
        if (minute) v = parseInt(v % 60 + "");
        var s: string = (year ? (year + "年") : "") + (months ? (months + "月") : "") + (day ? (day + "天") : "") + (hour ? (hour + "小时") : "") + (minute ? (minute + "分钟") : "") + (v ? ((v % 1 > 0 ? v.toFixed(1) : v) + "秒") : "")
        return s || "0秒";
    }

    //秒数转换成字符串 00:00:00
    var timeSign: Array<string> = new Array<string>(60);
    export function init(): void {
        for (var i: number = 0; i < 60; i++) {
            if (i < 10) {
                timeSign[i] = ":0" + i;
            } else {
                timeSign[i] = ":" + i;
            }
        }
    }
    init();
    export function toTime(second: number): string {
        if (second < 0) second = 0;
        var isH: Boolean;
        if (Math.floor(second / 3600) > 0) {
            isH = true;
        } else {
            isH = false;
        }
        var h: string = (second >= 36000 ? "" : "0") + Math.floor(second / 3600);

        var str: String = timeSign[Math.floor(second % 3600 / 60)] + timeSign[Math.floor(second % 60)];
        if (isH)
            return h + str;
        else
            return str.substr(1);
    }

    export function toTime1(second: number): string {
        if (second < 0) second = 0;
        var isH: Boolean;
        if (Math.floor(second / 3600) > 0) {
            isH = true;
        } else {
            isH = false;
        }
        var h: string = Math.floor(second / 3600) + "";

        var str: String = timeSign[Math.floor(second % 3600 / 60)];
        if (isH)
            return h + str;
        else
            return str.substr(1);
    }

    export function toClockHMS2(v: number): string {
        var hour: number = Math.floor(v / h);
        var minute: number = Math.floor((v % h) / 60);
        var sec = v % 60;
        if(hour == 0){
            return (minute < 10 ? "0" + minute : minute) + ":" + (sec < 10 ? "0" + sec : sec);
        }else{
            return (hour < 10 ? "0" + hour : hour) + "：" + (minute < 10 ? "0" + minute : minute) + ":" + (sec < 10 ? "0" + sec : sec);
        }
    }

    //hour:minute
    export function toClockHM(v: number): string {
        var hour: number = Math.floor(v / h);
        var minute: number = Math.floor((v % h) / 60);
        return (hour < 10 ? "0" + hour : hour) + "：" + (minute < 10 ? "0" + minute : minute);
    }
    //minute:second
    export function toClockMS(v: number): string {
        var minute = Math.floor((v % h) / 60);
        var sec = v % 60;
        return (minute < 10 ? "0" + minute : minute) + ":" + (sec < 10 ? "0" + sec : sec);
    }
    export function toClockMS2(v: number): string {
        var minute = Math.floor((v % h) / 60);
        var sec = v % 60;
        return (minute < 10 ? "0" + minute : minute) + "分" + (sec < 10 ? "0" + sec : sec) + "秒";
    }
    //hour:minute:second
    export function toClockHMS(v: number): string {
        var hour: number = Math.floor(v / h);
        var minute: number = Math.floor((v % h) / 60);
        var sec = v % 60;
        return (hour < 10 ? "0" + hour : hour) + "：" + (minute < 10 ? "0" + minute : minute) + "：" + (sec < 10 ? "0" + sec : sec);
    }
    export function toClockAuto(v: number) {
        var str: string;
        var h = Math.floor((v % 86400) / 3600);
        var m = Math.floor((v % 3600) / 60);
        if (v > 86400) {
            str = Math.floor(v / 86400) + "天";
            if (h > 0) str = str + h + "时";
        } else if (v > 3600) {
            str = h + "时";
            if (m > 0) str = str + m + "分";
        } else if (v > 60) {
            str = m + "分";
            if ((v % 60) > 0) str = str + (v % 60) + "秒";
        } else {
            str = v + "秒";
        }
        return str;
    }
    export function toDateYMD_HM(v: number): string {
        var date: Date = new Date;
        date.setTime(v * 1000);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();
        var h = date.getHours();
        var minute = date.getMinutes();
        return y + "-" + m + "-" + d + " " + h + ":" + (minute < 10 ? "0" + minute : minute);
    }
    export function toDateYMD(v: number): string {
        var date: Date = new Date;
        date.setTime(v * 1000);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();
        return y + "." + m + "." + d;
    }
    export function getRandomColor(): string {
        return '#' + Math.floor(Math.random() * 16777215).toString(16);
    }

    export function getDateStr(second: number): String {
        if (second < 0) second = 0;
        var h: string = Math.floor(second / 3600) + "";
        var minute: string = Math.floor(second % 3600 / 60) + "";
        return h + "时" + minute + "分";
    }

    export function format(v: number): string {
        if (v >= 1000000) {
            return Math.floor(v / 10000) + "万";
        }
        return v + "";
    }

    export function format2(v: number): string {
        if (v >= 100000000) {
            var w: number = Math.floor((v - 100000000) / 10000);
            return Math.floor(v / 100000000) + "亿" + ((w > 0) ? w + "万" : "");
        } else if (v >= 100000) {
            return Math.floor(v / 10000) + "万";
        }
        return v + "";
    }
    export function format3(v: number): string {
        if (v < 10000) return v + "";
        var n = Math.floor(v / 1000);
        var high = Math.floor(n / 10);
        var low = n % 10;
        if (low == 0) return high + "万";
        return high + "." + low + "万";
    }
    export function clone(obj: any): any {
        var o: any;
        if (obj.constructor == Object) {
            o = new obj.constructor();
        } else {
            o = new obj.constructor(obj.valueOf());
        }
        for (var key in obj) {
            if (o[key] != obj[key]) {
                if (typeof (obj[key]) == 'object') {
                    o[key] = clone(obj[key]);
                } else {
                    o[key] = obj[key];
                }
            }
        }
        o.toString = obj.toString;
        o.valueOf = obj.valueOf;
        return o;
    }

    /**
     * @param num  1-9
     * @return 中文数字
     */
    export function toChineseNum(num: number): string {
        var chineseStr: Array<string> = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
        var str: string = chineseStr[num];
        return str;
    }

    export function toChineseNum2(num: number): string {
        var strs: string = num + "";
        var str: string = "";
        for (var i = 0; i < strs.length; i++) {
            var s = strs[i];
            str += toChineseNum(Number(s));
        }
        return str;
    }


    var dict: Dictionary = new Dictionary();
    export function zoom(target: Sprite, startSpeed: number = 120, endSpeed: number = 200, scale: number = 1.15, callback: Function = null): void {

        if (dict.get(target)) return;
        dict.set(target, 1);
        var x: number = target.x;
        var y: number = target.y;
        var currentScale: number = target.scaleX;
        var offsetX: number = target.width * (scale - currentScale) / 2;
        var offsetY: number = target.height * (scale - currentScale) / 2;
        Tween.to(target, { x: x - offsetX, y: y - offsetY, scaleX: scale, scaleY: scale }, startSpeed, null, new Handler(this, function (target: Sprite) {
            Tween.to(target, { x: x, y: y, scaleX: 1, scaleY: 1 }, endSpeed, null, new Handler(this, onZoomcomplete, [target, callback]));
        }, [target]));

    }


    function onZoomcomplete(target: Sprite, callback: Function) {
        dict.remove(target);
        if (callback) callback();
    }

    var p: Laya.Point = new Laya.Point;
    export function getLineAngle(angle: number, len: number): Laya.Point {
        var a: number = angle * Math.PI / 180;

        p.x = Math.cos(a) * len;
        p.y = Math.sin(a) * len;
        return p;
    }
    //返回角度值
    export function getAngel(x: number, y: number, tx: number, ty: number): number {
        return Math.atan2(ty - y, tx - x) * 180 / Math.PI;
    }

    var tipsArray: Array<any> = [];
    var oldMsg: string = "";
    var isTimer: boolean = false;
    export function showTip(str, arr, y) {
        var strArray: Array<any> = [str, y];
        var bool: boolean = false;
        //判断重复的消息
        for (var i = 0; i < tipsArray.length; i++) {
            var obj: Array<any> = tipsArray[i];
            if (obj[0] == str) {
                bool = true;
            }
        }
        if (oldMsg != str && bool == false) {
            tipsArray.push(strArray);
        }
        if (isTimer == false) {
            runTips();
        }
    }

    function runTips(): void {
        if (tipsArray.length <= 0) {
            Laya.timer.clear(null, runTips);
            oldMsg = "";
            isTimer = false;
            return;
        }
        isTimer = true;
        var msgArry: Array<any> = tipsArray.shift();
        if (oldMsg == msgArry[0]) {
            msgArry = tipsArray.shift();
        }
        var tip: Laya.HTMLDivElement = tipPoolTop.pop();
        if (!tip) {
            tip = getText(Laya.stage.width);
        }
        tip.style.fontSize = 46;
        tip.y = msgArry[1];
        tip.innerHTML = msgArry[0];
        tip.alpha = 1;
        tip.width = Laya.stage.width;

        UIManager.broadLayer.addChild(tip);
        Tween.to(tip, { y: msgArry[1] - 65 }, 300, null, Handler.create(null, tween1, [tip, msgArry[1]]));
        Laya.timer.loop(550, null, runTips, [msgArry[1]]);
        oldMsg = msgArry[0];
    }

    function tween1(tip: Laya.HTMLDivElement, y: number): void {
        Tween.to(tip, { alpha: 1 }, 300, null, Handler.create(null, tween2, [tip, y]));
    }

    function tween2(tip: Laya.HTMLDivElement, y: any): void {
        Tween.to(tip, { y: y - 65, alpha: 0 }, 200, null, Handler.create(null, tween3, [tip]));
    }

    function tween3(tip: Laya.HTMLDivElement): void {
        tipPoolTop.push(tip);
        UIManager.broadLayer.removeChild(tip);
    }

    export function getText(width: number): Laya.HTMLDivElement {
        var tf: Laya.HTMLDivElement = new Laya.HTMLDivElement();
        tf.style.font = Global.font;
        tf.style.fontSize = 30;
        tf.style.color = "#FFFFFF";
        tf.style.strokeColor = "#342202";
        tf.style.stroke = 5;
        tf.width = width;
        tf.style.align = "center";
        return tf;
    }


    export function font(content: string, color: string, size: number = 12) {

        // "font:24px Arial' "
        return "<font color='" + color + "' style='font:" + size + "px " + Global.font + "'>" + content + "</font>";
    }


    export function  getImage(): Laya.Image {
        return Pool.getItemByCreateFun("Laya.Image", function (): Laya.Image {
            return new Laya.Image();
        });
    }

    export function clearGeneralHalf(){
        Utils.clearPrefix("res/generalHalf/");
    }
    export function clearPrefix(path:string){
        for (var url in Laya.Loader.loadedMap) {
            var tex = Laya.Loader.loadedMap[url];
            if (tex instanceof Texture) {
                if(tex.url != null && tex.url.indexOf(path) != -1){
                    if(tex.bitmap != null)(tex.bitmap as Bitmap).releaseResource();
                }
            }
        }
    }
    export function traceGeneralHalf(){
        console.log("generalHalf");
        for (var url in Laya.Loader.loadedMap) {
            var tex = Laya.Loader.loadedMap[url];
            if (tex instanceof Texture) {
                if(tex.url.indexOf("res/generalHalf/") != -1){
                    console.log(tex.url)
                }
            }
        }
    }
    export function traceCache(){
        var dict = {};
        for (var url in Laya.Loader.loadedMap) {
            var tex = Laya.Loader.loadedMap[url];
            if (tex instanceof Texture) {
                var bmp:Bitmap = tex.bitmap as Bitmap;
                if(bmp.url != null){
                    if(dict[bmp.url] != null)continue;
                    dict[bmp.url] = true;
                }
                var loadUrl = bmp.url != null ? bmp.url : tex.url;
                console.log(bmp.id,tex.url,tex.width,tex.height,bmp.url,bmp.width+","+bmp.height);
            }
        }
    }
    export function releaseTexture(url:string){
        let tex:Texture = Laya.loader.getRes(url);
        if(tex != null){
            var bmp:Bitmap = tex.bitmap;
            if(bmp != null){
                bmp.releaseResource();
                //console.log('强制释放', url);
            }
        }
    }
}

/**
 * Created by bobo on 2017/5/17.
 */
var strs = [];
var isDebug: boolean;
var isPhoneX: boolean;
function trace(...arg) {
    if (isDebug) {
        var debug = document.getElementById("debug");
        if (strs.length >= 50) strs.shift();
        var str = "";
        for (var i = 0; i < arguments.length; i++) {
            str += arguments[i];
            if (i < arguments.length - 1) str += ", ";
        }
        strs.push(str);
        str = "";
        for (var i = 0; i < strs.length; i++) {
            str += strs[i] + "<br>";
        }
        if (debug) debug.innerHTML = str;
    }
}

var tipPoolTop: Array<Laya.HTMLDivElement> = [];
var tipPoolCenter: Array<Laya.HTMLDivElement> = [];
var tipPoolBottom: Array<Laya.HTMLDivElement> = [];


function showCenterTip(str) {
    Utils.showTip(str, tipPoolCenter, 1136 / 2 + 200);
}

function showBottomTip(str) {
    Utils.showTip(str, tipPoolBottom, 870);
}

